//
//  LeftSortsViewController.m
//  LGDeckViewController
//
//  Created by jamie on 15/3/31.
//  Copyright (c) 2015年 Jamie-Ling. All rights reserved.
//

#import "LeftSortsViewController.h"
#import "AppDelegate.h"
#import "LeftMenuTableViewCell.h"
#import "MenuFootView.h"
#import "MenuHeadView.h"
#import "ProfileOneViewController.h"
#import "MyMoneyViewController.h"
#import "MyFormViewController.h"
#import "SettingMainViewController.h"
#import "MyBillsViewController.h"
#define LeftDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])
#define TABLEHEADHEIGHT 80
#define REMOVEWIDTH 100//菜单栏减少宽度
typedef NS_ENUM(NSInteger,TableIndex) {
    AreaIndex    = 0,
    ProfileIndex = 1,
    MoneyIndex   = 2,
    OrderIndex   = 3,
    BillIndex    = 4,
};
@interface LeftSortsViewController () <UITableViewDelegate,UITableViewDataSource,MenuFootViewDelegate,MenuHeadDelegate, CLLocationManagerDelegate,BMKGeoCodeSearchDelegate>

@property (nonatomic,retain) NSMutableArray   *tableData;

@property (nonatomic,retain) NSDictionary     *areaDic;

@property (nonatomic,retain) NSDictionary     *profileDic;

@property (nonatomic,retain) NSDictionary     *moneyDic;

@property (nonatomic,retain) NSDictionary     *orderDic;

@property (nonatomic,retain) NSDictionary     *accountDic;

@property (nonatomic,retain) NSDictionary     *messageDic;

@property (nonatomic,strong) MenuFootView     *menuFootV;

@property (nonatomic,strong) MenuHeadView     *menuHeadV;

@property (nonatomic,retain) CLLocationManager *locationManager;
///geo编码查询服务
@property (nonatomic,retain) BMKGeoCodeSearch *search;
///百度地图主引擎类
@property (nonatomic,retain) BMKMapManager    *mapManager;

@end

@implementation LeftSortsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self _initUI];
    // Do any additional setup after loading the view.
    
}

- (void)viewWillDisappear:(BOOL)animated {
    _search.delegate = nil;
}

//TODO:UI绘制
-(void)_initUI{
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageview.image = [UIImage imageNamed:@"menuBg"];
    [self.view addSubview:imageview];
    
    
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor clearColor];
    backView.frame = self.view.bounds;
    backView.tag = 1;
    [self.view addSubview:backView];
    
    [self initTableData];
    [backView addSubview:self.menuTable];
    
    //百度地图主引擎初始化，传递key
    _mapManager = [[BMKMapManager alloc] init];
    if ([_mapManager start:@"qxZEL3XDiFqztniaHYuHyQmC" generalDelegate:nil]) {
        NSLog(@"成功");
    }
    //geo编码查询服务初始化
    _search = [[BMKGeoCodeSearch alloc] init];
    _search.delegate = self;
    
    _menuFootV = [[MenuFootView alloc] initWithFrame:CGRectMake(20, ScreenHeihgt - 50, ScreenWidth - REMOVEWIDTH - 40, 40)];
    _menuFootV.menuFootdelegate = self;
    [backView addSubview:_menuFootV];
}
-(UIView *)getMenuTableHeadView{
    _menuHeadV = [[MenuHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - REMOVEWIDTH - 40, 70)];
    _menuHeadV.menuHeadDelegate = self;
    return _menuHeadV;
}
//TODO:重写get方法
-(UITableView *)menuTable{
    if (!_menuTable) {
        _menuTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, ScreenWidth - REMOVEWIDTH , ScreenHeihgt - 160)];
        _menuTable.backgroundColor = [UIColor clearColor];
        _menuTable.dataSource = self;
        _menuTable.delegate  = self;
        _menuTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _menuTable.tableHeaderView = [self getMenuTableHeadView];
    }
    return _menuTable;
}
//TODO:数据准备
/**
 *  初始化menutable 数据
 */
-(void)initTableData{
    
    _areaDic    = @{
                                        ICONIMAGE:@"gps",
                                        TITLE:USERCONTENT.getAreaMessgae == nil ? @"初始化定位":USERCONTENT.getAreaMessgae,
                                        ISFIRST : @(1)
                                     };
    
    _profileDic = @{
                                        ICONIMAGE:@"profile",
                                        TITLE:@"基本信息",
                                        ISFIRST : @(0)
                                        };
    _moneyDic   = @{
                                        ICONIMAGE:@"money",
                                        TITLE:@"我的钱包",
                                        ISFIRST : @(0)
                                      };
    
    _orderDic   = @{
                                        ICONIMAGE:@"order",
                                        TITLE:@"我的订单",
                                        ISFIRST : @(0)
                                      };
    
    _accountDic   = @{
                    ICONIMAGE:@"account",
                    TITLE:@"我的帐单",
                    ISFIRST : @(0)
                    };
    
    _messageDic   = @{
                    ICONIMAGE:@"message",
                    TITLE:@"我的消息",
                    ISFIRST : @(0)
                    };
    
    _tableData = [NSMutableArray arrayWithObjects:_areaDic,_profileDic,_moneyDic,_orderDic,_accountDic,_messageDic, nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//TODO:tableView delegate dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Identifier = @"Identifier";
    LeftMenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell == nil) {
        cell = [[LeftMenuTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
    }
    [cell setCellData:[_tableData objectAtIndex:indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == AreaIndex) {
        
        [self coreLocation];
    }else [LeftDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
//    [LeftDelegate.mainNavigationController pushViewController:vc animated:YES];
    if (indexPath.row == MoneyIndex) {
        MyMoneyViewController *myMoneyView = [[MyMoneyViewController alloc] init];
        [myMoneyView addCustomTitleWithTitle:@"我的钱包"];
        [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:myMoneyView];
    }
    if (indexPath.row == OrderIndex) {
        MyFormViewController *myFormView = [[MyFormViewController alloc] init];
        [myFormView addCustomTitleWithTitle:@"我的订单"];
        [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:myFormView];
    }
    if(indexPath.row == ProfileIndex){
        [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:[[ProfileOneViewController alloc] init]];
    }
    if (indexPath.row == BillIndex) {
        MyBillsViewController *myBillsView = [[MyBillsViewController alloc] init];
        [myBillsView addCustomTitleWithTitle:@"我的账单"];
        [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:myBillsView];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.menuTable.bounds.size.width, TABLEHEADHEIGHT)];
    view.backgroundColor = [UIColor clearColor];
    return nil;
}

//TODO:定位控制器的初始化 -- wangxin
- (void)coreLocation {
    
    _locationManager = [[CLLocationManager alloc] init];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    _locationManager.delegate = self;
    CLLocationDistance distance = 1000;
    _locationManager.distanceFilter = distance;
    bool enable = [CLLocationManager locationServicesEnabled];
    NSLog(@"%d",enable);
    int state = [CLLocationManager authorizationStatus];
    NSLog(@"%d",state);
    if (!enable || state < 3)
        [_locationManager requestAlwaysAuthorization];
    else
        [_locationManager startUpdatingLocation];

}

/** location -- wangxin
 *
 *  CLLocationManagerDelegate
 **/
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManager requestAlwaysAuthorization];
            }
            break;
            
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"error");
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    NSLog(@"经度：%f,纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    [manager stopUpdatingLocation];
    
    //发送地理坐标反编码
    BMKReverseGeoCodeOption *reversGeoCodeOption = [[BMKReverseGeoCodeOption alloc] init];
    reversGeoCodeOption.reverseGeoPoint = oldCoordinate;
    BOOL flag = [_search reverseGeoCode:reversGeoCodeOption];
    if (flag) {
        NSLog(@"发送成功");
    }else
        NSLog(@"发送失败");
    
}

//TODO:百度反geo编码回调
/** BMKGeoCodeSearchDelegate -- wangxin
 **/
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        NSString *info = result.addressDetail.city;
        if ([info isEqualToString:@""]) {
            info = @"初始化定位";
            [SVProgressHUD showAlertView:@"所在城市获取失败" andMessage:@"所在地点所属城市信息无法获取"];
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_areaDic];
        [dic setObject:info forKey:TITLE];
        [USERCONTENT setAreaMessage:info];
        _areaDic = (NSDictionary *)dic;
        [self reloadArea];
    }else {
        [SVProgressHUD showAlertView:@"所在城市获取失败" andMessage:@"所在地点所属城市信息无法获取"];
    }
}

//TODO:menuFootdelegate
-(void)menuFootClickLoginOut{
    [self showSVProgressSuccess:@"注销"];
//    [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:[[BaseViewController alloc] init]];
}
-(void)menuFootClickSet{
    [LeftDelegate.LeftSlideVC closeLeftView];
    [self showSVProgressSuccess:@"设置"];
    [[NSNotificationCenter defaultCenter] postNotificationName:ROOTGOTONEXTCONTROLLER object:[[SettingMainViewController alloc] init]];
}
//TODO:menuHeadDelegate
-(void) clickMenuHead{
    
}
//TODO: ACTION
/**
 *  定位信息获取后重新刷新menutbale 
 */
-(void)reloadArea{
    [_tableData removeAllObjects];
    [_tableData addObject:_areaDic];
    [_tableData addObject:_profileDic];
    [_tableData addObject:_moneyDic];
    [_tableData addObject:_orderDic];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.menuTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationRight];
}
@end
